// 模拟数据
const mockStocks = [
    { code: '600000', name: '浦发银行', price: 10.25, change: 0.52, open: 10.10, high: 10.30, low: 10.05, volume: 150000 },
    { code: '000001', name: '平安银行', price: 15.30, change: -1.23, open: 15.40, high: 15.45, low: 15.10, volume: 220000 },
    { code: '601318', name: '中国平安', price: 48.75, change: 2.15, open: 48.00, high: 48.90, low: 47.80, volume: 350000 },
    { code: '600519', name: '贵州茅台', price: 1720.50, change: 1.85, open: 1710.00, high: 1725.00, low: 1705.00, volume: 50000 }
];

// 添加股票历史数据
const stockHistoricalData = {
    '600000': generateHistoricalData(10.10, 30),
    '000001': generateHistoricalData(15.40, 30),
    '601318': generateHistoricalData(48.00, 30),
    '600519': generateHistoricalData(1710.00, 30)
};

// 生成历史数据的函数
function generateHistoricalData(startPrice, days) {
    const data = [];
    let currentPrice = startPrice;
    
    for (let i = days; i >= 0; i--) {
        // 生成随机波动
        const changePercent = (Math.random() - 0.5) * 0.04; // 日涨跌幅在-2%到2%之间
        const newPrice = currentPrice * (1 + changePercent);
        
        // 计算最高价和最低价
        const high = Math.max(currentPrice, newPrice) * (1 + Math.random() * 0.01);
        const low = Math.min(currentPrice, newPrice) * (1 - Math.random() * 0.01);
        
        // 成交量
        const volume = Math.floor(Math.random() * 500000) + 100000;
        
        data.push({
            date: new Date(Date.now() - i * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
            open: currentPrice,
            close: newPrice,
            high: high,
            low: low,
            volume: volume
        });
        
        currentPrice = newPrice;
    }
    
    return data;
}

// 用户账户数据
let account = {
    balance: 1000000,
    positions: []
};

// 策略数据存储
let strategies = JSON.parse(localStorage.getItem('tradingStrategies')) || [];

// 数学函数扩展
const mathFunctions = {
    log: Math.log,
    log10: Math.log10,
    exp: Math.exp,
    sqrt: Math.sqrt,
    pow: Math.pow,
    abs: Math.abs
};

// Quantitative functions
const quantFunctions = {
    rank: (arr, value) => {
        const sorted = [...arr].sort((a, b) => a - b);
        return sorted.indexOf(value) + 1;
    },
    scale: (value, min, max) => {
        return (value - min) / (max - min);
    },
    corr: (arr1, arr2, window) => {
        const slice1 = arr1.slice(-window);
        const slice2 = arr2.slice(-window);
        const mean1 = slice1.reduce((a, b) => a + b, 0) / window;
        const mean2 = slice2.reduce((a, b) => a + b, 0) / window;
        let cov = 0, std1 = 0, std2 = 0;
        for(let i = 0; i < window; i++) {
            cov += (slice1[i] - mean1) * (slice2[i] - mean2);
            std1 += Math.pow(slice1[i] - mean1, 2);
            std2 += Math.pow(slice2[i] - mean2, 2);
        }
        return cov / (Math.sqrt(std1) * Math.sqrt(std2));
    }
};

// 示例股票数据
const sampleStockData = [
    { code: '600000', name: '浦发银行', open: 10.2, close: 10.5, high: 10.8, low: 10.1, volume: 500000 },
    { code: '600036', name: '招商银行', open: 35.6, close: 36.2, high: 36.5, low: 35.3, volume: 300000 },
    { code: '601318', name: '中国平安', open: 48.3, close: 47.8, high: 48.7, low: 47.5, volume: 800000 }
];

// 自定义字段存储
let customFields = JSON.parse(localStorage.getItem('customFields') || '[]');

// 模拟多个策略收益数据
const strategyPerformanceData = {
    'strategy_1': [
        { date: '2023-01-01', value: 0 },
        { date: '2023-01-02', value: 1.2 },
        { date: '2023-01-03', value: 2.5 },
        { date: '2023-01-04', value: 1.8 },
        { date: '2023-01-05', value: 3.2 },
        { date: '2023-01-06', value: 4.1 },
        { date: '2023-01-07', value: 3.7 }
    ],
    'strategy_2': [
        { date: '2023-01-01', value: 0 },
        { date: '2023-01-02', value: 0.8 },
        { date: '2023-01-03', value: 1.5 },
        { date: '2023-01-04', value: 2.1 },
        { date: '2023-01-05', value: 1.9 },
        { date: '2023-01-06', value: 2.6 },
        { date: '2023-01-07', value: 3.2 }
    ],
    'strategy_3': [
        { date: '2023-01-01', value: 0 },
        { date: '2023-01-02', value: -0.5 },
        { date: '2023-01-03', value: 0.2 },
        { date: '2023-01-04', value: 1.1 },
        { date: '2023-01-05', value: 0.8 },
        { date: '2023-01-06', value: 1.4 },
        { date: '2023-01-07', value: 1.9 }
    ]
};

document.addEventListener('DOMContentLoaded', () => {
    renderMarketTable();
    renderStockTable();
    updateAccountInfo();
    renderPortfolioTable();
    setupNavigation();
    setupEventListeners();
    
    // 只在策略页面初始化
    const strategyPage = document.getElementById('strategy-page');
    if (strategyPage) {
        renderStrategyList();
        renderCustomFieldsList();
        renderPreviewTable();
        setupFieldManagementEvents();
        setupStrategyEditorEvents();
    }
    
    // 在首页添加策略收益图表
    const dashboardPage = document.getElementById('dashboard-page');
    if (dashboardPage) {
        renderStrategyPerformanceChart();
    }
});

function setupNavigation() {
    const navItems = document.querySelectorAll('.nav-item');
    navItems.forEach(item => {
        item.addEventListener('click', () => {
            // Remove active class from all items
            navItems.forEach(navItem => {
                navItem.classList.remove('active-nav');
            });
            
            // Add active class to clicked item
            item.classList.add('active-nav');
            
            // Hide all pages
            document.querySelectorAll('.page').forEach(page => {
                page.classList.remove('active');
            });
            
            // Show target page
            const targetPage = item.getAttribute('data-target');
            document.getElementById(targetPage).classList.add('active');
        });
    });
}

// 添加渲染策略收益图表的函数
function renderStrategyPerformanceChart() {
    const chartContainer = document.createElement('div');
    chartContainer.className = 'bg-white rounded-xl shadow-md p-6 mb-6';
    chartContainer.innerHTML = `
        <h2 class="text-xl font-semibold mb-4">策略收益</h2>
        <div id="strategy-charts-container"></div>
    `;
    
    // 插入到账户概览之后
    const accountOverview = document.querySelector('#dashboard-page .bg-white.rounded-xl.shadow-md.p-6.mb-6');
    accountOverview.after(chartContainer);
    
    // 绘制所有策略图表
    drawAllStrategyCharts();
}

// 绘制所有策略收益图表
function drawAllStrategyCharts() {
    const container = document.getElementById('strategy-charts-container');
    if (!container) return;
    
    // 清空容器
    container.innerHTML = '';
    
    // 为每个策略创建图表
    Object.keys(strategyPerformanceData).forEach(strategyId => {
        const chartWrapper = document.createElement('div');
        chartWrapper.className = 'strategy-chart-wrapper mb-6';
        chartWrapper.innerHTML = `
            <div class="flex justify-between items-center mb-2">
                <h3 class="font-medium">策略 ${strategyId.split('_')[1]}</h3>
                <button class="text-blue-500 text-sm view-strategy-detail" data-strategy="${strategyId}">
                    查看详情 <i class="fas fa-arrow-right"></i>
                </button>
            </div>
            <canvas id="strategy-chart-${strategyId}" height="150"></canvas>
        `;
        container.appendChild(chartWrapper);
    });
    
    // 绘制每个图表
    Object.keys(strategyPerformanceData).forEach(strategyId => {
        drawStrategyChart(strategyId);
    });
    
    // 绑定查看详情事件
    document.querySelectorAll('.view-strategy-detail').forEach(button => {
        button.addEventListener('click', function() {
            const strategyId = this.getAttribute('data-strategy');
            showStrategyDetail(strategyId);
        });
    });
}

// 绘制单个策略收益图表
function drawStrategyChart(strategyId) {
    const canvas = document.getElementById(`strategy-chart-${strategyId}`);
    if (!canvas) return;
    
    const ctx = canvas.getContext('2d');
    const chartWidth = canvas.width;
    const chartHeight = canvas.height;
    
    // 清空画布
    ctx.clearRect(0, 0, chartWidth, chartHeight);
    
    const data = strategyPerformanceData[strategyId];
    
    // 设置图表边距
    const margin = { top: 10, right: 10, bottom: 20, left: 40 };
    const width = chartWidth - margin.left - margin.right;
    const height = chartHeight - margin.top - margin.bottom;
    
    // 找到最大值和最小值
    const values = data.map(d => d.value);
    const maxValue = Math.max(...values);
    const minValue = Math.min(...values);
    const valueRange = maxValue - minValue || 1; // 防止除零
    
    // 绘制坐标轴
    ctx.beginPath();
    ctx.strokeStyle = '#ccc';
    ctx.lineWidth = 1;
    
    // Y轴
    ctx.moveTo(margin.left, margin.top);
    ctx.lineTo(margin.left, margin.top + height);
    
    // X轴
    ctx.moveTo(margin.left, margin.top + height);
    ctx.lineTo(margin.left + width, margin.top + height);
    ctx.stroke();
    
    // 绘制网格线和标签
    ctx.fillStyle = '#666';
    ctx.font = '10px Arial';
    ctx.textAlign = 'right';
    
    // Y轴标签和网格线
    const yTicks = 3;
    for (let i = 0; i <= yTicks; i++) {
        const y = margin.top + height - (i / yTicks) * height;
        const value = minValue + (i / yTicks) * valueRange;
        
        // 网格线
        ctx.beginPath();
        ctx.strokeStyle = '#eee';
        ctx.moveTo(margin.left, y);
        ctx.lineTo(margin.left + width, y);
        ctx.stroke();
        
        // 标签
        ctx.fillText(value.toFixed(1) + '%', margin.left - 5, y + 3);
    }
    
    // X轴标签
    ctx.textAlign = 'center';
    const xTicks = Math.min(data.length, 3); // 只显示开始、中间和结束日期
    for (let i = 0; i < xTicks; i++) {
        const dataIndex = i === 0 ? 0 : 
                         i === 1 ? Math.floor(data.length / 2) : 
                         data.length - 1;
        const x = margin.left + (dataIndex / (data.length - 1)) * width;
        ctx.fillText(data[dataIndex].date.substring(5), x, margin.top + height + 15);
    }
    
    // 绘制折线
    ctx.beginPath();
    ctx.strokeStyle = '#3b82f6';
    ctx.lineWidth = 2;
    
    for (let i = 0; i < data.length; i++) {
        const x = margin.left + (i / (data.length - 1)) * width;
        const y = margin.top + height - ((data[i].value - minValue) / valueRange) * height;
        
        if (i === 0) {
            ctx.moveTo(x, y);
        } else {
            ctx.lineTo(x, y);
        }
    }
    ctx.stroke();
    
    // 绘制数据点
    ctx.fillStyle = '#3b82f6';
    for (let i = 0; i < data.length; i++) {
        const x = margin.left + (i / (data.length - 1)) * width;
        const y = margin.top + height - ((data[i].value - minValue) / valueRange) * height;
        
        ctx.beginPath();
        ctx.arc(x, y, 3, 0, Math.PI * 2);
        ctx.fill();
    }
    
    // 显示最终收益值
    const finalValue = data[data.length - 1].value;
    ctx.fillStyle = finalValue >= 0 ? '#ef4444' : '#10b981';
    ctx.font = 'bold 12px Arial';
    ctx.textAlign = 'right';
    ctx.fillText(finalValue.toFixed(2) + '%', chartWidth - 5, 15);
}

// 显示策略详情
function showStrategyDetail(strategyId) {
    const data = strategyPerformanceData[strategyId];
    if (!data) return;
    
    // 创建模态框
    const modal = document.createElement('div');
    modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
    modal.innerHTML = `
        <div class="bg-white rounded-xl shadow-lg w-11/12 max-w-2xl max-h-[90vh] overflow-auto">
            <div class="p-6">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-xl font-semibold">策略 ${strategyId.split('_')[1]} 详情</h3>
                    <button class="close-modal text-gray-500 hover:text-gray-700">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="mb-6">
                    <canvas id="detail-strategy-chart" height="300"></canvas>
                </div>
                <div class="mb-6">
                    <h4 class="font-medium mb-2">收益数据</h4>
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">日期</th>
                                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">收益 (%)</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200">
                                ${data.map(item => `
                                    <tr>
                                        <td class="px-4 py-2 whitespace-nowrap">${item.date}</td>
                                        <td class="px-4 py-2 whitespace-nowrap ${item.value >= 0 ? 'text-red-500' : 'text-green-500'}">
                                            ${item.value >= 0 ? '+' : ''}${item.value.toFixed(2)}%
                                        </td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    </div>
                </div>
                <div>
                    <h4 class="font-medium mb-2">交易详情</h4>
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">日期</th>
                                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">股票代码</th>
                                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">股票名称</th>
                                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">操作</th>
                                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">价格</th>
                                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">数量</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200">
                                <!-- 示例交易数据 -->
                                <tr>
                                    <td class="px-4 py-2 whitespace-nowrap">2023-01-02</td>
                                    <td class="px-4 py-2 whitespace-nowrap">600000</td>
                                    <td class="px-4 py-2 whitespace-nowrap">浦发银行</td>
                                    <td class="px-4 py-2 whitespace-nowrap text-green-500">买入</td>
                                    <td class="px-4 py-2 whitespace-nowrap">10.25</td>
                                    <td class="px-4 py-2 whitespace-nowrap">1000</td>
                                </tr>
                                <tr>
                                    <td class="px-4 py-2 whitespace-nowrap">2023-01-04</td>
                                    <td class="px-4 py-2 whitespace-nowrap">600036</td>
                                    <td class="px-4 py-2 whitespace-nowrap">招商银行</td>
                                    <td class="px-4 py-2 whitespace-nowrap text-red-500">卖出</td>
                                    <td class="px-4 py-2 whitespace-nowrap">36.10</td>
                                    <td class="px-4 py-2 whitespace-nowrap">500</td>
                                </tr>
                                <tr>
                                    <td class="px-4 py-2 whitespace-nowrap">2023-01-05</td>
                                    <td class="px-4 py-2 whitespace-nowrap">601318</td>
                                    <td class="px-4 py-2 whitespace-nowrap">中国平安</td>
                                    <td class="px-4 py-2 whitespace-nowrap text-green-500">买入</td>
                                    <td class="px-4 py-2 whitespace-nowrap">47.90</td>
                                    <td class="px-4 py-2 whitespace-nowrap">800</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    // 绘制详细图表
    setTimeout(() => {
        drawDetailStrategyChart(strategyId);
    }, 100);
    
    // 绑定关闭事件
    modal.querySelector('.close-modal').addEventListener('click', () => {
        document.body.removeChild(modal);
    });
    
    // 点击背景关闭
    modal.addEventListener('click', (e) => {
        if (e.target === modal) {
            document.body.removeChild(modal);
        }
    });
}

// 绘制详细策略收益图表
function drawDetailStrategyChart(strategyId) {
    const canvas = document.getElementById('detail-strategy-chart');
    if (!canvas) return;
    
    const ctx = canvas.getContext('2d');
    const chartWidth = canvas.width;
    const chartHeight = canvas.height;
    
    // 清空画布
    ctx.clearRect(0, 0, chartWidth, chartHeight);
    
    const data = strategyPerformanceData[strategyId];
    
    // 设置图表边距
    const margin = { top: 20, right: 20, bottom: 40, left: 60 };
    const width = chartWidth - margin.left - margin.right;
    const height = chartHeight - margin.top - margin.bottom;
    
    // 找到最大值和最小值
    const values = data.map(d => d.value);
    const maxValue = Math.max(...values);
    const minValue = Math.min(...values);
    const valueRange = maxValue - minValue || 1; // 防止除零
    
    // 绘制坐标轴
    ctx.beginPath();
    ctx.strokeStyle = '#ccc';
    ctx.lineWidth = 1;
    
    // Y轴
    ctx.moveTo(margin.left, margin.top);
    ctx.lineTo(margin.left, margin.top + height);
    
    // X轴
    ctx.moveTo(margin.left, margin.top + height);
    ctx.lineTo(margin.left + width, margin.top + height);
    ctx.stroke();
    
    // 绘制网格线和标签
    ctx.fillStyle = '#666';
    ctx.font = '12px Arial';
    ctx.textAlign = 'right';
    
    // Y轴标签和网格线
    const yTicks = 5;
    for (let i = 0; i <= yTicks; i++) {
        const y = margin.top + height - (i / yTicks) * height;
        const value = minValue + (i / yTicks) * valueRange;
        
        // 网格线
        ctx.beginPath();
        ctx.strokeStyle = '#eee';
        ctx.moveTo(margin.left, y);
        ctx.lineTo(margin.left + width, y);
        ctx.stroke();
        
        // 标签
        ctx.fillText(value.toFixed(1) + '%', margin.left - 5, y + 4);
    }
    
    // X轴标签
    ctx.textAlign = 'center';
    const xTicks = Math.min(data.length, 7); // 最多显示7个日期标签
    for (let i = 0; i < data.length; i++) {
        // 只在特定位置显示标签
        if (data.length <= 7 || i % Math.floor(data.length / (xTicks - 1)) === 0 || i === data.length - 1) {
            const x = margin.left + (i / (data.length - 1)) * width;
            ctx.fillText(data[i].date.substring(5), x, margin.top + height + 20);
        }
    }
    
    // 绘制折线
    ctx.beginPath();
    ctx.strokeStyle = '#3b82f6';
    ctx.lineWidth = 2;
    
    for (let i = 0; i < data.length; i++) {
        const x = margin.left + (i / (data.length - 1)) * width;
        const y = margin.top + height - ((data[i].value - minValue) / valueRange) * height;
        
        if (i === 0) {
            ctx.moveTo(x, y);
        } else {
            ctx.lineTo(x, y);
        }
    }
    ctx.stroke();
    
    // 绘制数据点
    ctx.fillStyle = '#3b82f6';
    for (let i = 0; i < data.length; i++) {
        const x = margin.left + (i / (data.length - 1)) * width;
        const y = margin.top + height - ((data[i].value - minValue) / valueRange) * height;
        
        ctx.beginPath();
        ctx.arc(x, y, 4, 0, Math.PI * 2);
        ctx.fill();
    }
}

function renderMarketTable() {
    const tbody = document.getElementById('market-table');
    tbody.innerHTML = mockStocks.map(stock => `
        <tr class="hover:bg-gray-50">
            <td class="px-6 py-4 whitespace-nowrap font-medium">${stock.code}</td>
            <td class="px-6 py-4 whitespace-nowrap">${stock.name}</td>
            <td class="px-6 py-4 whitespace-nowrap">${stock.price.toFixed(2)}</td>
            <td class="px-6 py-4 whitespace-nowrap ${stock.change >= 0 ? 'text-red-500' : 'text-green-500'}">
                ${stock.change >= 0 ? '+' : ''}${stock.change.toFixed(2)}%
            </td>
        </tr>
    `).join('');
    
    // 为市场动态表格添加折线图组件
    addLineChartComponents();
}

// 添加折线图组件（替代原来的K线图）
function addLineChartComponents() {
    const marketRows = document.querySelectorAll('#market-table tr');
    
    marketRows.forEach((row, index) => {
        if (index === 0) return; // 跳过表头
        
        const stock = mockStocks[index - 1];
        if (!stock) return;
        
        // 创建折线图容器
        const lineChartCell = document.createElement('td');
        lineChartCell.className = 'px-6 py-4 whitespace-nowrap';
        lineChartCell.innerHTML = `
            <div class="line-chart" style="width: 100px; height: 50px; position: relative; cursor: pointer;" data-stock="${stock.code}">
                <canvas class="line-chart-canvas" data-stock="${stock.code}" width="100" height="50"></canvas>
            </div>
        `;
        
        // 插入到涨跌幅列之后
        const changeCell = row.querySelector('td:last-child');
        changeCell.parentNode.insertBefore(lineChartCell, changeCell.nextSibling);
        
        // 添加点击事件
        lineChartCell.addEventListener('click', () => {
            showStockDetail(stock.code);
        });
    });
    
    // 绘制所有折线图
    drawLineCharts();
}

// 绘制折线图
function drawLineCharts() {
    const canvases = document.querySelectorAll('.line-chart-canvas');
    
    canvases.forEach(canvas => {
        const ctx = canvas.getContext('2d');
        const stockCode = canvas.getAttribute('data-stock');
        const stock = mockStocks.find(s => s.code === stockCode);
        const historicalData = stockHistoricalData[stockCode];
        
        if (!stock || !historicalData) return;
        
        const width = canvas.width;
        const height = canvas.height;
        
        // 清空画布
        ctx.clearRect(0, 0, width, height);
        
        // 获取最近30天的收盘价
        const prices = historicalData.map(d => d.close);
        
        // 计算价格范围
        const maxPrice = Math.max(...prices);
        const minPrice = Math.min(...prices);
        const priceRange = maxPrice - minPrice || 0.1; // 防止除零
        
        // 绘制折线图
        ctx.beginPath();
        ctx.strokeStyle = stock.change >= 0 ? '#f87171' : '#34d399'; // 红色涨/绿色跌
        ctx.lineWidth = 2;
        
        for (let i = 0; i < prices.length; i++) {
            const x = (i / (prices.length - 1)) * width;
            const y = height - ((prices[i] - minPrice) / priceRange) * height;
            
            if (i === 0) {
                ctx.moveTo(x, y);
            } else {
                ctx.lineTo(x, y);
            }
        }
        ctx.stroke();
    });
}

// 显示股票详情
function showStockDetail(stockCode) {
    const stock = mockStocks.find(s => s.code === stockCode);
    if (!stock) return;
    
    // 切换到交易页面
    document.querySelectorAll('.nav-item').forEach(item => {
        item.classList.remove('active-nav');
    });
    const tradePageNavItem = document.querySelector('[data-target="trade-page"]');
    if (tradePageNavItem) {
        tradePageNavItem.classList.add('active-nav');
    }
    
    document.querySelectorAll('.page').forEach(page => {
        page.classList.remove('active');
    });
    const tradePage = document.getElementById('trade-page');
    if (tradePage) {
        tradePage.classList.add('active');
    }
    
    // 填充股票代码
    const stockCodeInput = document.getElementById('stock-code');
    if (stockCodeInput) {
        stockCodeInput.value = stockCode;
    }
    
    // 创建K线图详情
    createKLineDetail(stock);
}

// 创建K线图详情
function createKLineDetail(stock) {
    // 查找或创建K线图容器
    let kLineContainer = document.getElementById('k-line-detail-container');
    if (!kLineContainer) {
        kLineContainer = document.createElement('div');
        kLineContainer.id = 'k-line-detail-container';
        kLineContainer.className = 'bg-white rounded-xl shadow-md p-6 mb-6';
        kLineContainer.innerHTML = `
            <h2 class="text-xl font-semibold mb-4">${stock.name} (${stock.code}) K线图</h2>
            <div class="k-line-detail" style="width: 100%; height: 300px; position: relative;">
                <canvas id="k-line-detail-canvas"></canvas>
            </div>
        `;
        
        // 插入到交易表单之前
        const tradeForm = document.getElementById('trade-form');
        if (tradeForm) {
            tradeForm.parentNode.insertBefore(kLineContainer, tradeForm);
        }
    } else {
        // 更新标题
        kLineContainer.querySelector('h2').textContent = `${stock.name} (${stock.code}) K线图`;
    }
    
    // 设置画布大小
    const canvas = document.getElementById('k-line-detail-canvas');
    if (canvas) {
        canvas.width = kLineContainer.querySelector('.k-line-detail').offsetWidth;
        canvas.height = 300;
        drawKLineDetail(canvas, stock);
    }
}

// 绘制K线图详情
function drawKLineDetail(canvas, stock) {
    const ctx = canvas.getContext('2d');
    const width = canvas.width;
    const height = canvas.height;
    
    // 清空画布
    ctx.clearRect(0, 0, width, height);
    
    // 获取股票历史数据
    const historicalData = stockHistoricalData[stock.code] || [];
    
    if (historicalData.length === 0) {
        // 如果没有历史数据，显示错误信息
        ctx.fillStyle = '#666';
        ctx.font = '16px Arial';
        ctx.textAlign = 'center';
        ctx.fillText('暂无历史数据', width/2, height/2);
        return;
    }
    
    // 使用历史数据绘制K线图
    const padding = { top: 20, right: 50, bottom: 30, left: 40 };
    const chartWidth = width - padding.left - padding.right;
    const chartHeight = height - padding.top - padding.bottom;
    
    // 计算价格范围
    let minPrice = Infinity;
    let maxPrice = -Infinity;
    
    historicalData.forEach(day => {
        if (day.low < minPrice) minPrice = day.low;
        if (day.high > maxPrice) maxPrice = day.high;
    });
    
    // 添加一些价格边距
    const pricePadding = (maxPrice - minPrice) * 0.05;
    minPrice -= pricePadding;
    maxPrice += pricePadding;
    
    const priceRange = maxPrice - minPrice;
    
    // 绘制坐标轴
    ctx.beginPath();
    ctx.strokeStyle = '#ccc';
    ctx.lineWidth = 1;
    
    // Y轴
    ctx.moveTo(padding.left, padding.top);
    ctx.lineTo(padding.left, padding.top + chartHeight);
    
    // X轴
    ctx.moveTo(padding.left, padding.top + chartHeight);
    ctx.lineTo(padding.left + chartWidth, padding.top + chartHeight);
    ctx.stroke();
    
    // 绘制网格线和标签
    ctx.fillStyle = '#666';
    ctx.font = '10px Arial';
    ctx.textAlign = 'right';
    
    // Y轴标签和网格线
    const yTicks = 5;
    for (let i = 0; i <= yTicks; i++) {
        const y = padding.top + chartHeight - (i / yTicks) * chartHeight;
        const price = minPrice + (i / yTicks) * priceRange;
        
        // 网格线
        ctx.beginPath();
        ctx.strokeStyle = '#eee';
        ctx.moveTo(padding.left, y);
        ctx.lineTo(padding.left + chartWidth, y);
        ctx.stroke();
        
        // 标签
        ctx.fillText(price.toFixed(2), padding.left - 5, y + 3);
    }
    
    // X轴标签 (显示一周的日期)
    ctx.textAlign = 'center';
    const xTicks = Math.min(historicalData.length, 7); // 最多显示7个日期标签
    for (let i = 0; i < historicalData.length; i += Math.ceil(historicalData.length / xTicks)) {
        const x = padding.left + (i / (historicalData.length - 1)) * chartWidth;
        const date = historicalData[i].date;
        ctx.fillText(date.substring(5), x, padding.top + chartHeight + 15);
    }
    
    // 绘制K线
    const candleWidth = Math.max(1, chartWidth / historicalData.length - 2);
    
    for (let i = 0; i < historicalData.length; i++) {
        const day = historicalData[i];
        const x = padding.left + (i / (historicalData.length - 1)) * chartWidth;
        
        // 计算Y坐标
        const openY = padding.top + chartHeight - ((day.open - minPrice) / priceRange) * chartHeight;
        const closeY = padding.top + chartHeight - ((day.close - minPrice) / priceRange) * chartHeight;
        const highY = padding.top + chartHeight - ((day.high - minPrice) / priceRange) * chartHeight;
        const lowY = padding.top + chartHeight - ((day.low - minPrice) / priceRange) * chartHeight;
        
        // 确定颜色 (收盘价高于开盘价为涨)
        const isUp = day.close >= day.open;
        ctx.fillStyle = isUp ? '#f87171' : '#34d399'; // 红色涨/绿色跌
        ctx.strokeStyle = isUp ? '#f87171' : '#34d399';
        
        // 绘制最高价和最低价的线
        ctx.beginPath();
        ctx.moveTo(x, highY);
        ctx.lineTo(x, lowY);
        ctx.stroke();
        
        // 绘制K线主体
        const topY = Math.min(openY, closeY);
        const bodyHeight = Math.abs(closeY - openY);
        
        if (bodyHeight < 1) {
            // 十字星
            ctx.beginPath();
            ctx.moveTo(x - candleWidth/2, topY);
            ctx.lineTo(x + candleWidth/2, topY);
            ctx.stroke();
        } else {
            // 正常K线
            ctx.fillRect(x - candleWidth/2, topY, candleWidth, bodyHeight);
            ctx.strokeRect(x - candleWidth/2, topY, candleWidth, bodyHeight);
        }
    }
    
    // 添加标题
    ctx.fillStyle = '#333';
    ctx.font = '14px Arial';
    ctx.textAlign = 'center';
    ctx.fillText(`${stock.name} (${stock.code}) 近一个月K线图`, width/2, 15);
}

function renderStockTable() {
    const tbody = document.getElementById('stock-table');
    tbody.innerHTML = mockStocks.map(stock => `
        <tr class="hover:bg-gray-50">
            <td class="px-6 py-4 whitespace-nowrap font-medium">${stock.code}</td>
            <td class="px-6 py-4 whitespace-nowrap">${stock.name}</td>
            <td class="px-6 py-4 whitespace-nowrap">${stock.price.toFixed(2)}</td>
            <td class="px-6 py-4 whitespace-nowrap ${stock.change >= 0 ? 'text-red-500' : 'text-green-500'}">
                ${stock.change >= 0 ? '+' : ''}${stock.change.toFixed(2)}%
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
                <button class="trade-btn px-3 py-1 bg-blue-100 text-blue-600 rounded text-sm" 
                        data-code="${stock.code}">交易</button>
            </td>
        </tr>
    `).join('');
}

function renderPortfolioTable() {
    const tbody = document.getElementById('portfolio-table');
    if (account.positions.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="6" class="px-6 py-4 text-center text-gray-500">
                    暂无持仓
                </td>
            </tr>
        `;
        return;
    }

    tbody.innerHTML = account.positions.map(position => {
        const stock = mockStocks.find(s => s.code === position.code);
        const currentPrice = stock ? stock.price : position.cost;
        const profit = (currentPrice - position.cost) * position.amount;
        const profitPercent = ((currentPrice / position.cost) - 1) * 100;
        
        return `
            <tr class="hover:bg-gray-50">
                <td class="px-6 py-4 whitespace-nowrap font-medium">${position.code}</td>
                <td class="px-6 py-4 whitespace-nowrap">${position.name}</td>
                <td class="px-6 py-4 whitespace-nowrap">${position.amount}</td>
                <td class="px-6 py-4 whitespace-nowrap">${position.cost.toFixed(2)}</td>
                <td class="px-6 py-4 whitespace-nowrap">${currentPrice.toFixed(2)}</td>
                <td class="px-6 py-4 whitespace-nowrap ${profit >= 0 ? 'text-red-500' : 'text-green-500'}">
                    ${profit >= 0 ? '+' : ''}${profit.toFixed(2)} (${profitPercent.toFixed(2)}%)
                </td>
            </tr>
        `;
    }).join('');
}

function updateAccountInfo() {
    document.getElementById('available-balance').textContent = account.balance.toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    });

    // 计算总资产（持仓市值 + 可用资金）
    const positionValue = account.positions.reduce((sum, pos) => {
        const stock = mockStocks.find(s => s.code === pos.code);
        return sum + (stock ? stock.price * pos.amount : 0);
    }, 0);

    const totalAssets = account.balance + positionValue;
    document.getElementById('total-assets').textContent = totalAssets.toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    });

    // 计算持仓收益
    const positionProfit = account.positions.reduce((sum, pos) => {
        const stock = mockStocks.find(s => s.code === pos.code);
        return sum + (stock ? (stock.price - pos.cost) * pos.amount : 0);
    }, 0);

    const profitElement = document.getElementById('position-profit');
    profitElement.textContent = positionProfit.toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    });
    profitElement.className = positionProfit >= 0 ? 
        'text-2xl font-bold text-red-500' : 
        'text-2xl font-bold text-green-500';
}

function renderStrategyList() {
    const tbody = document.getElementById('strategy-list');
    if (!tbody) return; // 如果不在策略页面则返回
    
    if (strategies.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="5" class="p-3 text-center text-gray-500">
                    暂无策略
                </td>
            </tr>
        `;
        return;
    }

    tbody.innerHTML = strategies.map(strategy => `
        <tr>
            <td class="p-3">${strategy.name}</td>
            <td class="p-3">${getStrategyTypeName(strategy.type)}</td>
            <td class="p-3">
                <span class="px-2 py-1 rounded-full text-xs ${strategy.active ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'}">
                    ${strategy.active ? '运行中' : '已停止'}
                </span>
            </td>
            <td class="p-3">0.00%</td>
            <td class="p-3 space-x-2">
                <button class="text-blue-500 edit-strategy-btn" data-id="${strategy.id}">
                    <i class="fas fa-edit"></i>
                </button>
                <button class="text-green-500 toggle-strategy-btn" data-id="${strategy.id}">
                    ${strategy.active ? '<i class="fas fa-pause"></i>' : '<i class="fas fa-play"></i>'}
                </button>
                <button class="text-red-500 delete-strategy-btn" data-id="${strategy.id}">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        </tr>
    `).join('');
    
    // 绑定编辑、切换和删除事件
    document.querySelectorAll('.edit-strategy-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const strategyId = this.getAttribute('data-id');
            editStrategy(strategyId);
        });
    });
    
    document.querySelectorAll('.toggle-strategy-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const strategyId = this.getAttribute('data-id');
            toggleStrategy(strategyId);
        });
    });
    
    document.querySelectorAll('.delete-strategy-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const strategyId = this.getAttribute('data-id');
            deleteStrategy(strategyId);
        });
    });
}

function getStrategyTypeName(type) {
    const types = {
        'turtle': '海龟交易',
        'golden_cross': '均线金叉',
        'moving_average': '均线策略',
        'custom': '自定义'
    };
    return types[type] || '未知';
}

function setupEventListeners() {
    // 价格类型切换
    const priceType = document.getElementById('price-type');
    if (priceType) {
        priceType.addEventListener('change', (e) => {
            const limitPriceGroup = document.getElementById('limit-price-group');
            if (limitPriceGroup) {
                limitPriceGroup.classList.toggle('hidden', e.target.value !== 'limit');
            }
        });
    }

    // 股票代码自动填充
    document.querySelectorAll('.trade-btn').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const code = e.target.dataset.code;
            const stockCodeInput = document.getElementById('stock-code');
            if (stockCodeInput) {
                stockCodeInput.value = code;
            }
            
            // Switch to trade page
            document.querySelectorAll('.nav-item').forEach(item => {
                item.classList.remove('active-nav');
            });
            const tradePageNavItem = document.querySelector('[data-target="trade-page"]');
            if (tradePageNavItem) {
                tradePageNavItem.classList.add('active-nav');
            }
            
            document.querySelectorAll('.page').forEach(page => {
                page.classList.remove('active');
            });
            const tradePage = document.getElementById('trade-page');
            if (tradePage) {
                tradePage.classList.add('active');
            }
        });
    });

    // 刷新按钮
    const refreshBtn = document.getElementById('refresh-btn');
    if (refreshBtn) {
        refreshBtn.addEventListener('click', () => {
            renderStockTable();
        });
    }

    // 表单提交
    const tradeForm = document.getElementById('trade-form');
    if (tradeForm) {
        tradeForm.addEventListener('submit', (e) => {
            e.preventDefault();
            executeTrade();
        });
    }

    // 新建策略按钮
    const newStrategyBtn = document.getElementById('btn-new-strategy');
    if (newStrategyBtn) {
        newStrategyBtn.addEventListener('click', () => {
            alert('跳转到策略创建页面');
        });
    }
}

function executeTrade() {
    const code = document.getElementById('stock-code').value;
    const type = document.getElementById('trade-type').value;
    const priceType = document.getElementById('price-type').value;
    const amount = parseInt(document.getElementById('trade-amount').value);
    const limitPrice = parseFloat(document.getElementById('limit-price').value);

    if (!code || !amount) {
        alert('请填写完整交易信息');
        return;
    }

    const stock = mockStocks.find(s => s.code === code);
    if (!stock) {
        alert('未找到该股票');
        return;
    }

    const price = priceType === 'market' ? stock.price : limitPrice;

    if (type === 'buy') {
        // 买入逻辑
        const cost = price * amount;
        if (cost > account.balance) {
            alert('可用资金不足');
            return;
        }

        account.balance -= cost;
        const existingPos = account.positions.find(p => p.code === code);
        if (existingPos) {
            existingPos.amount += amount;
            existingPos.cost = ((existingPos.cost * existingPos.amount) + cost) / (existingPos.amount + amount);
        } else {
            account.positions.push({
                code,
                name: stock.name,
                amount,
                cost: price,
                buyDate: new Date().toISOString()
            });
        }
    } else {
        // 卖出逻辑
        const position = account.positions.find(p => p.code === code);
        if (!position || position.amount < amount) {
            alert('持仓不足');
            return;
        }

        account.balance += price * amount;
        position.amount -= amount;

        if (position.amount === 0) {
            account.positions = account.positions.filter(p => p.code !== code);
        }
    }

    updateAccountInfo();
    renderPortfolioTable();
    alert(`委托成功：${type === 'buy' ? '买入' : '卖出'} ${stock.name} ${amount}股`);
    document.getElementById('trade-form').reset();
}

// 编辑策略
function editStrategy(strategyId) {
    const strategy = strategies.find(s => s.id === strategyId);
    if (!strategy) return;
    
    // 填充表单
    const strategyNameInput = document.getElementById('strategy-name');
    const strategyTemplateSelect = document.getElementById('strategy-template');
    const strategyCodeTextarea = document.getElementById('strategy-code');
    
    if (strategyNameInput) strategyNameInput.value = strategy.name;
    if (strategyTemplateSelect) strategyTemplateSelect.value = strategy.type;
    if (strategyCodeTextarea) strategyCodeTextarea.value = strategy.code;
    
    // 显示对应参数面板
    document.querySelectorAll('.strategy-params').forEach(el => {
        el.classList.add('hidden');
    });
    
    if (strategy.type) {
        const paramsElement = document.getElementById(`${strategy.type}-params`);
        if (paramsElement) {
            paramsElement.classList.remove('hidden');
        }
        
        // 填充参数值
        if (strategy.type === 'turtle') {
            const input2 = document.querySelector('#turtle-params input:nth-child(2)');
            const input4 = document.querySelector('#turtle-params input:nth-child(4)');
            const input6 = document.querySelector('#turtle-params input:nth-child(6)');
            
            if (input2) input2.value = strategy.params.breakoutDays || 20;
            if (input4) input4.value = strategy.params.atrMultiplier || 2;
            if (input6) input6.value = strategy.params.positionRatio || 1;
        } else if (strategy.type === 'golden_cross') {
            const input2 = document.querySelector('#golden-cross-params input:nth-child(2)');
            const input4 = document.querySelector('#golden-cross-params input:nth-child(4)');
            const input6 = document.querySelector('#golden-cross-params input:nth-child(6)');
            
            if (input2) input2.value = strategy.params.shortPeriod || 5;
            if (input4) input4.value = strategy.params.longPeriod || 10;
            if (input6) input6.value = strategy.params.volumeThreshold || 1000;
        } else if (strategy.type === 'moving_average') {
            const input2 = document.querySelector('#moving-average-params input:nth-child(2)');
            const input4 = document.querySelector('#moving-average-params input:nth-child(4)');
            
            if (input2) input2.value = strategy.params.period || 10;
            if (input4) input4.value = strategy.params.deviationPercent || 2;
        }
    }
}

// 切换策略状态
function toggleStrategy(strategyId) {
    strategies = strategies.map(strategy => {
        if (strategy.id === strategyId) {
            strategy.active = !strategy.active;
        }
        return strategy;
    });
    
    localStorage.setItem('tradingStrategies', JSON.stringify(strategies));
    renderStrategyList();
}

// 删除策略
function deleteStrategy(strategyId) {
    if (confirm('确定要删除这个策略吗？')) {
        strategies = strategies.filter(strategy => strategy.id !== strategyId);
        localStorage.setItem('tradingStrategies', JSON.stringify(strategies));
        renderStrategyList();
    }
}

// 设置策略编辑器事件监听器
function setupStrategyEditorEvents() {
    // 策略模板选择
    const strategyTemplate = document.getElementById('strategy-template');
    if (strategyTemplate) {
        strategyTemplate.addEventListener('change', function() {
            // 隐藏所有参数面板
            document.querySelectorAll('.strategy-params').forEach(el => {
                el.classList.add('hidden');
            });
            
            // 显示选中的参数面板
            const template = this.value;
            if (template) {
                const paramsElement = document.getElementById(`${template}-params`);
                if (paramsElement) {
                    paramsElement.classList.remove('hidden');
                }
            }
        });
    }
    
    // 代码编辑器语言标签切换
    const languageTabs = document.querySelectorAll('#strategy-page .border-b button');
    languageTabs.forEach(tab => {
        tab.addEventListener('click', function() {
            // 移除所有标签的激活状态
            languageTabs.forEach(t => t.classList.remove('bg-gray-100'));
            // 添加当前标签的激活状态
            this.classList.add('bg-gray-100');
        });
    });
    
    // 加载模板按钮
    const loadTemplateBtn = document.getElementById('load-template-btn');
    if (loadTemplateBtn) {
        loadTemplateBtn.addEventListener('click', function() {
            const template = document.getElementById('strategy-template')?.value;
            const strategyName = document.getElementById('strategy-name')?.value || '新策略';
            
            let codeTemplate = '';
            switch(template) {
                case 'turtle':
                    codeTemplate = `/* 海龟交易策略
 * 基于突破的交易系统，使用ATR止损
 */
function turtleStrategy(data, params) {
    const breakoutDays = params.breakoutDays || 20;
    const atrMultiplier = params.atrMultiplier || 2;
    const positionRatio = params.positionRatio || 1;
    
    // 计算过去N天的最高价和最低价
    const highs = data.high.slice(-breakoutDays);
    const lows = data.low.slice(-breakoutDays);
    const highestHigh = Math.max(...highs);
    const lowestLow = Math.min(...lows);
    
    // 计算ATR
    const atr = calculateATR(data, 14);
    
    const lastClose = data.close[data.close.length - 1];
    
    // 入场信号
    if (lastClose > highestHigh) {
        return {
            action: 'buy',
            price: highestHigh,
            stopLoss: highestHigh - (atr * atrMultiplier),
            positionSize: positionRatio
        };
    } else if (lastClose < lowestLow) {
        return {
            action: 'sell',
            price: lowestLow,
            stopLoss: lowestLow + (atr * atrMultiplier),
            positionSize: positionRatio
        };
    }
    
    return null;
}

// 计算ATR函数
function calculateATR(data, period) {
    let tr = [];
    for (let i = 1; i < data.close.length; i++) {
        const todayHigh = data.high[i];
        const todayLow = data.low[i];
        const yesterdayClose = data.close[i-1];
        
        const tr1 = todayHigh - todayLow;
        const tr2 = Math.abs(todayHigh - yesterdayClose);
        const tr3 = Math.abs(todayLow - yesterdayClose);
        
        tr.push(Math.max(tr1, tr2, tr3));
    }
    
    // 计算ATR
    let atr = tr.slice(0, period).reduce((a, b) => a + b, 0) / period;
    for (let i = period; i < tr.length; i++) {
        atr = (atr * (period - 1) + tr[i]) / period;
    }
    
    return atr;
}`;
                    break;
                    
                case 'golden_cross':
                    codeTemplate = `/* 均线金叉策略
 * 当短期均线上穿长期均线时买入，下穿时卖出
 */
function goldenCrossStrategy(data, params) {
    const shortPeriod = params.shortPeriod || 5;
    const longPeriod = params.longPeriod || 10;
    const volumeThreshold = params.volumeThreshold || 1000;
    
    // 计算均线
    const shortMA = calculateMA(data.close, shortPeriod);
    const longMA = calculateMA(data.close, longPeriod);
    
    const lastShortMA = shortMA[shortMA.length - 1];
    const lastLongMA = longMA[longMA.length - 1];
    const prevShortMA = shortMA[shortMA.length - 2];
    const prevLongMA = longMA[longMA.length - 2];
    
    const lastVolume = data.volume[data.volume.length - 1];
    
    // 金叉买入信号
    if (lastShortMA > lastLongMA && prevShortMA <= prevLongMA && lastVolume >= volumeThreshold) {
        return {
            action: 'buy',
            price: data.close[data.close.length - 1],
            comment: '均线金叉'
        };
    }
    
    // 死叉卖出信号
    if (lastShortMA < lastLongMA && prevShortMA >= prevLongMA) {
        return {
            action: 'sell',
            price: data.close[data.close.length - 1],
            comment: '均线死叉'
        };
    }
    
    return null;
}

// 计算简单移动平均线
function calculateMA(data, period) {
    let ma = [];
    for (let i = period - 1; i < data.length; i++) {
        const sum = data.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0);
        ma.push(sum / period);
    }
    return ma;
}`;
                    break;
                    
                case 'moving_average':
                    codeTemplate = `/* 均线回归策略
 * 当价格偏离均线一定比例时进行反向操作
 */
function movingAverageStrategy(data, params) {
    const period = params.period || 10;
    const deviationPercent = params.deviationPercent || 2;
    
    // 计算均线
    const ma = calculateMA(data.close, period);
    const lastMA = ma[ma.length - 1];
    const lastClose = data.close[data.close.length - 1];
    
    // 计算偏离比例
    const deviation = (lastClose - lastMA) / lastMA * 100;
    
    // 超卖买入信号
    if (deviation < -deviationPercent) {
        return {
            action: 'buy',
            price: lastClose,
            comment: '价格低于均线' + Math.abs(deviation).toFixed(2) + '%'
        };
    }
    
    // 超买卖出信号
    if (deviation > deviationPercent) {
        return {
            action: 'sell',
            price: lastClose,
            comment: '价格高于均线' + deviation.toFixed(2) + '%'
        };
    }
    
    return null;
}

// 计算简单移动平均线
function calculateMA(data, period) {
    let ma = [];
    for (let i = period - 1; i < data.length; i++) {
        const sum = data.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0);
        ma.push(sum / period);
    }
    return ma;
}`;
                    break;
                    
                default:
                    codeTemplate = `/* 
 * 自定义策略模板
 * 可用变量:
 * - data: 包含open,high,low,close,volume等历史数据
 * - params: 自定义参数对象
 */

function customStrategy(data, params) {
    /* 可用数据:
    - data.open: 开盘价数组
    - data.high: 最高价数组
    - data.low: 最低价数组
    - data.close: 收盘价数组
    - data.volume: 成交量数组
    - params: 策略参数对象
    */
    
    // 示例策略逻辑
    const lastClose = data.close[data.close.length - 1];
    const prevClose = data.close[data.close.length - 2];
    
    if (lastClose > prevClose) {
        return {
            signal: 'BUY',
            price: lastClose,
            comment: '价格上涨趋势'
        };
    }
    
    return null;
}`;
            }
            
            const strategyCode = document.getElementById('strategy-code');
            if (strategyCode) {
                strategyCode.value = codeTemplate;
            }
        });
    }
    
    // 保存策略按钮
    const saveStrategyBtn = document.getElementById('save-strategy-btn');
    if (saveStrategyBtn) {
        saveStrategyBtn.addEventListener('click', function() {
            const strategyName = document.getElementById('strategy-name')?.value || '未命名策略';
            const strategyCode = document.getElementById('strategy-code')?.value;
            const strategyTemplate = document.getElementById('strategy-template')?.value;
            
            // 收集参数
            const params = {};
            if (strategyTemplate === 'turtle') {
                params.breakoutDays = document.querySelector('#turtle-params input:nth-child(2)')?.value || 20;
                params.atrMultiplier = document.querySelector('#turtle-params input:nth-child(4)')?.value || 2;
                params.positionRatio = document.querySelector('#turtle-params input:nth-child(6)')?.value || 1;
            } else if (strategyTemplate === 'golden_cross') {
                params.shortPeriod = document.querySelector('#golden-cross-params input:nth-child(2)')?.value || 5;
                params.longPeriod = document.querySelector('#golden-cross-params input:nth-child(4)')?.value || 10;
                params.volumeThreshold = document.querySelector('#golden-cross-params input:nth-child(6)')?.value || 1000;
            } else if (strategyTemplate === 'moving_average') {
                params.period = document.querySelector('#moving-average-params input:nth-child(2)')?.value || 10;
                params.deviationPercent = document.querySelector('#moving-average-params input:nth-child(4)')?.value || 2;
            }
            
            // 创建新策略对象
            const newStrategy = {
                id: Date.now().toString(),
                name: strategyName,
                type: strategyTemplate || 'custom',
                code: strategyCode,
                params: params,
                active: false,
                createdAt: new Date().toISOString(),
                performance: []
            };
            
            // 保存到策略列表
            strategies.push(newStrategy);
            localStorage.setItem('tradingStrategies', JSON.stringify(strategies));
            
            // 更新策略列表显示
            renderStrategyList();
            
            alert('策略保存成功！');
        });
    }
    
    // 验证策略按钮
    const validateStrategyBtn = document.getElementById('validate-strategy-btn');
    if (validateStrategyBtn) {
        validateStrategyBtn.addEventListener('click', function() {
            const strategyCode = document.getElementById('strategy-code')?.value;
            
            try {
                // 简单验证代码语法
                new Function(strategyCode);
                alert('策略代码语法正确！');
            } catch (e) {
                alert('策略代码存在语法错误：' + e.message);
            }
        });
    }
}

// 设置字段管理事件监听器
function setupFieldManagementEvents() {
    const addFieldBtn = document.getElementById('add-field-btn');
    if (addFieldBtn) {
        addFieldBtn.addEventListener('click', function() {
            const fieldName = document.getElementById('new-field-name')?.value.trim();
            const formula = document.getElementById('field-formula')?.value.trim();
            
            if (!fieldName || !formula) {
                alert('请输入字段名称和公式');
                return;
            }
            
            // 验证公式
            try {
                // 创建测试数据
                const testData = sampleStockData[0];
                const allData = sampleStockData;
                
                // 解析并测试公式
                evaluateFormula(formula, testData, allData);
                
                // 添加新字段
                customFields.push({
                    id: fieldName.toLowerCase().replace(/\s+/g, '_'),
                    name: fieldName,
                    formula: formula
                });
                
                // 保存到localStorage
                localStorage.setItem('customFields', JSON.stringify(customFields));
                
                // 更新UI
                renderCustomFieldsList();
                renderPreviewTable();
                
                // 清空输入
                if (document.getElementById('new-field-name')) {
                    document.getElementById('new-field-name').value = '';
                }
                if (document.getElementById('field-formula')) {
                    document.getElementById('field-formula').value = '';
                }
            } catch (e) {
                alert('公式错误: ' + e.message);
            }
        });
    }
}

// 解析并计算公式
function evaluateFormula(formula, rowData, allData) {
    try {
        // 替换数学函数调用
        let processedFormula = formula.replace(
            /(log|log10|exp|sqrt|pow|abs)\(/g, 
            'mathFunctions.$1('
        );
        
        // 替换quant函数调用
        processedFormula = processedFormula.replace(
            /(rank|scale|corr)\(/g, 
            'quantFunctions.$1('
        );
        
        // 创建计算函数
        const calcFunction = new Function(
            'row', 
            'mathFunctions', 
            'quantFunctions', 
            'allData', 
            `return ${processedFormula};`
        );
        
        return calcFunction(rowData, mathFunctions, quantFunctions, allData);
    } catch (e) {
        throw new Error('公式解析失败: ' + e.message);
    }
}

// 渲染自定义字段列表
function renderCustomFieldsList() {
    const container = document.getElementById('custom-fields-list');
    if (!container) return;
    
    if (customFields.length === 0) {
        container.innerHTML = '<tr><td colspan="3" class="p-3 text-center text-gray-500">暂无自定义字段</td></tr>';
        return;
    }
    
    container.innerHTML = customFields.map(field => `
        <tr>
            <td class="p-3 border">${field.name}</td>
            <td class="p-3 border font-mono text-sm">${field.formula}</td>
            <td class="p-3 border">
                <button class="remove-field-btn bg-red-500 text-white px-2 py-1 rounded text-sm" 
                        data-field-id="${field.id}">
                    删除
                </button>
            </td>
        </tr>
    `).join('');
    
    // 绑定删除事件
    document.querySelectorAll('.remove-field-btn').forEach(button => {
        button.addEventListener('click', function() {
            const fieldId = this.getAttribute('data-field-id');
            customFields = customFields.filter(f => f.id !== fieldId);
            localStorage.setItem('customFields', JSON.stringify(customFields));
            renderCustomFieldsList();
            renderPreviewTable();
        });
    });
}

// 渲染预览表格
function renderPreviewTable() {
    // 更新表头
    const headerRow = document.getElementById('preview-table-header');
    if (!headerRow) return;
    
    let headerHtml = `
        <th class="p-2 border">代码</th>
        <th class="p-2 border">名称</th>
        <th class="p-2 border">开盘价</th>
        <th class="p-2 border">收盘价</th>
        <th class="p-2 border">最高价</th>
        <th class="p-2 border">最低价</th>
        <th class="p-2 border">成交量</th>
    `;
    
    // 添加自定义字段列
    customFields.forEach(field => {
        headerHtml += `<th class="p-2 border">${field.name}</th>`;
    });
    
    headerRow.innerHTML = headerHtml;
    
    // 更新表体
    const bodyContainer = document.getElementById('preview-table-body');
    if (!bodyContainer) return;
    
    bodyContainer.innerHTML = sampleStockData.map(stock => {
        let rowHtml = `
            <tr>
                <td class="p-2 border">${stock.code}</td>
                <td class="p-2 border">${stock.name}</td>
                <td class="p-2 border">${stock.open}</td>
                <td class="p-2 border">${stock.close}</td>
                <td class="p-2 border">${stock.high}</td>
                <td class="p-2 border">${stock.low}</td>
                <td class="p-2 border">${stock.volume}</td>
        `;
        
        // 计算并添加自定义字段值
        customFields.forEach(field => {
            try {
                const value = evaluateFormula(field.formula, stock, sampleStockData);
                rowHtml += `<td class="p-2 border">${typeof value === 'number' ? value.toFixed(4) : value}</td>`;
            } catch (e) {
                rowHtml += `<td class="p-2 border text-red-500">Error</td>`;
            }
        });
        
        rowHtml += '</tr>';
        return rowHtml;
    }).join('');
}